import React, { Component } from 'react';
import {connect} from 'react-redux';

import { List, Avatar} from 'antd-mobile';

class Msg extends Component {
    render() {
        console.log(this.props);
        let loginUserId = this.props.state.registerReducer._id;
        let chatUsers = {};
        this.props.state.msgReducer.msgLst.forEach(el => {
            // 把所有聊天的用户放在一个对象中，每个用户的聊天信息是一个数组，所有聊天记录放入数组中
            chatUsers[el.chatId] = chatUsers[el.chatId] || [];
            chatUsers[el.chatId].push(el);
        })
        // 获取对象中每一下的key
        let chatList = Object.values(chatUsers);
        console.log(chatList);
        // 获取当前聊天对象的用户名
        const getChatUserName = (userId) => {
            for(var i = 0; i < this.props.state.userList.userListArr.length; i++) {
                if(this.props.state.userList.userListArr[i]._id === userId) {
                    return this.props.state.userList.userListArr[i].user;
                }
            }
        }
        return (
            <div>
                {chatList.map(item => (
                    <List key={item[0]._id} bordered="true">
                        <List.Item>
                            {item[item.length-1].content}
                            <List.Item.Brief>
                                {loginUserId===item[0].to?getChatUserName(item[0].from):getChatUserName(item[0].to)}
                            </List.Item.Brief>
                        </List.Item>
                    </List>
                ))}
            </div>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        state:state
    }    
}
export default connect(mapStateToProps)(Msg);
